<script setup lang="ts" name="RoleDrawer">
import { base } from '@/api/public'
import { menu } from '@/api/settings'
import { getDepartmentList } from '@/api/department'
import useDictionaryEntry from '@/hooks/useDictionaryEntry'
import { cloneDeep } from 'lodash-es'
import { dataToTree, treeData, treeFormat } from '@/utils'
import { transformI18n } from '@/plugins/i18n'
const { getDictionaryEntryData } = useDictionaryEntry()
const visible = ref(false)
const title = ref('')

const initInfo = ref({
  menuList: [],
  expandNodes: [],
  checkedNodes: []
})

const showDrawer = (v) => {
  console.log(v)
  visible.value = true
  title.value = v.name
  getMenuListData()
  getDepartmentData()
}
// 子组件将方法暴露给父组件
defineExpose({ showDrawer })

const cancelClick = () => {
  visible.value = false
}

const confirmClick = () => {
  console.log('保存')
}

const dataAuthorizationCollapse = ref(['read', 'edit', 'delete'])
const handleAuthorizationChange = (val: string[]) => {
  console.log(val)
}

const dataFieldCollapse = ref(['EpComprehensiveForm'])
const handleFieldChange = (val: string[]) => {
  console.log(val)
}

const dataValueCollapse = ref(['Home'])
const handleValueChange = (val: string[]) => {
  console.log(val)
}

const formData = ref({
  menu: [],
  data: {
    read: 1,
    edit: 1,
    delete: 1
  },
  field: {},
  value: {
    home: {
      module: []
    }
  }
})

const departmentList = ref([])
// 获取当前查询条件下的数据
const getDepartmentData = () => {
  const result: any = {}
  result.name = ''
  getDepartmentList(result, { config: { showLoading: false, mockEnable: true } }).then((res:any) => {
    console.log(res)
    if (res.data && res.data.length > 0) {
      setTimeout(() => {
        const departList = dataToTree(cloneDeep(res.data), 0, 'pid', 'id')
        treeData(departList, false, [], 0)
        treeFormat(departList, 'name', 'id')
        departmentList.value = departList
      }, 1000)
    }
  })
}

const departTreeProps = ref({
  children: 'children',
  label: 'label'
})

const handleNodeClick = (data) => {
  console.log(data)
}

// 树形控件选择事件
const handleCheckChange = (data, checked, indeterminate) => {
  console.log(data, checked, indeterminate)
}

const permissionsDataTypeList = ref([])
const getPermissionsDataTypeList = async () => {
  permissionsDataTypeList.value = await getDictionaryEntryData({
    label: '',
    status: 2,
    type: 'permissionsDataType'
  })
}
getPermissionsDataTypeList()

const homeModuleTypeList = ref([])
const getHomeModuleTypeList = async () => {
  homeModuleTypeList.value = await getDictionaryEntryData({
    label: '',
    status: 2,
    type: 'homeModuleType'
  })
}
getHomeModuleTypeList()

const comprehensiveFormFieldList = ref([])
const getComprehensiveFormFieldList = async () => {
  comprehensiveFormFieldList.value = await getDictionaryEntryData({
    label: '',
    status: 2,
    type: 'comprehensiveFormField'
  })
}
getComprehensiveFormFieldList()

const totalWidth = ref(0)
// 获取当前查询条件下的数据
const getMenuListData = () => {
  const result: any = {}
  result.title = ''
  result.status = 1
  menu.search(result, { config: { showLoading: false, mockEnable: true } }).then((res:any) => {
    console.log(res)
    if (res.data && res.data.length > 0) {
      setTimeout(() => {
        const menuResult: any = {}
        menuResult.menuID = ''
        menuResult.label = ''
        menuResult.value = ''
        menuResult.requestType = ''
        base.menuPermit(menuResult, { config: { showLoading: false, mockEnable: true } }).then((res2:any) => {
          console.log(res2)
          if (res2.data && res2.data.length > 0) {
            setTimeout(() => {
              res.data.forEach((item) => {
                item.menuPermissionsButtonList = []
                item.checkedList = []
                const textArr = []
                if (!item.isCatalog) {
                  res2.data.forEach((current) => {
                    if (item.id === current.menuID) {
                      textArr.push(current.label)
                      item.menuPermissionsButtonList.push(current)
                    }
                  })
                  const itemWidth = getTextWidth(textArr.join(''))
                  const otherWidth = (22 + 30) * item.menuPermissionsButtonList.length + 24 + 8
                  if (itemWidth + otherWidth > totalWidth.value) {
                    totalWidth.value = itemWidth + otherWidth
                  }
                }
              })
              const menuList = dataToTree(cloneDeep(res.data), 0, 'pid', 'id')
              treeData(menuList, false, [], 0)
              treeFormat(menuList, 'name', 'id')
              initInfo.value.menuList = menuList
            }, 1000)
          }
        })
      }, 1000)
    }
  })
}

const menuSelectionChange = (v) => {
  console.log(v)
}

const readDepartmentSelectionChange = (v) => {
  console.log(v)
}

const getTextWidth = (text) => {
  const span = document.createElement('span')
  span.style.visibility = 'hidden'
  span.style.position = 'absolute'
  span.style.top = '-9999px'
  span.style.whiteSpace = 'nowrap'
  span.style.fontSize = '18px'
  span.innerText = text
  document.body.appendChild(span)
  const width = span.offsetWidth
  document.body.removeChild(span)
  return width
}

const defaultExpandNodes = (data) => {
  data.forEach((item) => {
    if (item.type === 'category') {
      initInfo.value.expandNodes.push(item.id)
    }
    if (item.children && item.children.length < 0 && item.type !== 'button') {
      defaultExpandNodes(item.children)
    }
  })
}
</script>

<template>
  <el-drawer class="role-drawer" v-model="visible" direction="rtl" size="70%">
    <template #header>
      <h2>
        {{ $t('buttons.buttonCurrent') }}{{ $t('page.角色') }}
        <el-tag class="ml-10px">{{ title }}</el-tag>
      </h2>
    </template>
    <template #default>
      <div class="tab-wrap">
        <el-tabs tab-position="left">
          <el-tab-pane :label="$t('page.菜单授权')">
            <div class="table-layout">
              <div class="table-wrapper">
                <div class="table-wrap">
                  <el-table :data="initInfo.menuList" border default-expand-all row-key="id" @selection-change="menuSelectionChange">
                    <el-table-column type="selection" width="44" fixed="left" />
                    <el-table-column prop="title" :label="$t('page.菜单名称')" width="280" fixed="left">
                      <template #default="scope">
                        {{ transformI18n('menus.' + scope.row.title, true) }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="menuPermissionsButtonList" :label="$t('page.权限名称')" :min-width="totalWidth">
                      <template #default="scope">
                        <el-checkbox-group v-model="scope.row.checkList">
                          <el-checkbox v-for="(item, index) in scope.row.menuPermissionsButtonList" :key="index" :label="transformI18n('menus.' + item.label, true)" />
                        </el-checkbox-group>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane :label="$t('page.数据授权')">
            <el-scrollbar>
              <el-collapse v-model="dataAuthorizationCollapse" @change="handleAuthorizationChange">
                <el-collapse-item name="read">
                  <template #title>
                    <el-tag>{{ $t('buttons.buttonCanView') }}</el-tag>
                  </template>
                  <el-form>
                    <el-form-item>
                      <el-radio-group class="radio-button" v-model="formData.data.read">
                        <el-radio-button v-for="(item, index) in permissionsDataTypeList" :key="index" :label="item.value" border>{{ $t('page.' + item.label ) }}</el-radio-button>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item v-if="formData.data.read === 4">
                      <div class="table-content">
                        <el-table :data="departmentList" border default-expand-all row-key="id" width="100%" :height="480" @selection-change="readDepartmentSelectionChange">
                          <el-table-column type="selection" width="44" fixed="left" />
                          <el-table-column prop="label" :label="$t('page.部门名称')" />
                        </el-table>
                      </div>
                    </el-form-item>
                  </el-form>
                </el-collapse-item>
                <el-collapse-item name="edit">
                  <template #title>
                    <el-tag>{{ $t('buttons.buttonCanEdit') }}</el-tag>
                  </template>
                  <el-form>
                    <el-form-item>
                      <el-radio-group class="radio-button" v-model="formData.data.edit">
                        <el-radio-button v-for="(item, index) in permissionsDataTypeList" :key="index" :label="item.value" border>{{ $t('page.' + item.label ) }}</el-radio-button>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item v-if="formData.data.edit === 4">
                      <div class="table-content">
                        <el-table :data="departmentList" border default-expand-all row-key="id" width="100%" :height="480" @selection-change="readDepartmentSelectionChange">
                          <el-table-column type="selection" width="44" fixed="left" />
                          <el-table-column prop="label" :label="$t('page.部门名称')" />
                        </el-table>
                      </div>
                    </el-form-item>
                  </el-form>
                </el-collapse-item>
                <el-collapse-item name="delete">
                  <template #title>
                    <el-tag>{{ $t('buttons.buttonCanRemove') }}</el-tag>
                  </template>
                  <el-form>
                    <el-form-item>
                      <el-radio-group class="radio-button" v-model="formData.data.delete">
                        <el-radio-button v-for="(item, index) in permissionsDataTypeList" :key="index" :label="item.value" border>{{ $t('page.' + item.label ) }}</el-radio-button>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item v-if="formData.data.delete === 4">
                      <div class="table-content">
                        <el-table :data="departmentList" border default-expand-all row-key="id" width="100%" :height="480" @selection-change="readDepartmentSelectionChange">
                          <el-table-column type="selection" width="44" fixed="left" />
                          <el-table-column prop="label" :label="$t('page.部门名称')" />
                        </el-table>
                      </div>
                    </el-form-item>
                  </el-form>
                </el-collapse-item>
              </el-collapse>
            </el-scrollbar>
          </el-tab-pane>
          <el-tab-pane :label="$t('page.字段授权')">
            <el-scrollbar>
              <el-collapse v-model="dataFieldCollapse" @change="handleFieldChange">
                <el-collapse-item name="EpComprehensiveForm">
                  <template #title>
                    <el-tag>{{ $t('menus.组件') }} / {{ $t('menus.element-plus') }} / {{ $t('menus.表单') }} / {{ $t('menus.综合表单') }}</el-tag>
                  </template>
                  <el-table :data="comprehensiveFormFieldList" border>
                    <el-table-column prop="label" :label="$t('page.字段名称')">
                      <template #default="scope">
                        {{ $t('page.' + scope.row.label) }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="value" :label="$t('page.字段标识')" />
                    <el-table-column :label="$t('page.权限配置')" align="center">
                      <el-table-column width="100" align="center">
                        <template #header>
                          <el-checkbox :label="1">{{ $t('buttons.buttonView') }}</el-checkbox>
                        </template>
                        <template #default="scope">
                          <el-checkbox :label="scope.row.id">{{ '' }}</el-checkbox>
                        </template>
                      </el-table-column>
                      <el-table-column width="100" align="center">
                        <template #header>
                          <el-checkbox :label="1">{{ $t('buttons.buttonEdit') }}</el-checkbox>
                        </template>
                        <template #default="scope">
                          <el-checkbox :label="scope.row.id">{{ '' }}</el-checkbox>
                        </template>
                      </el-table-column>
                    </el-table-column>
                  </el-table>
                </el-collapse-item>
              </el-collapse>
            </el-scrollbar>
          </el-tab-pane>
          <el-tab-pane :label="$t('page.模块授权')">
            <el-scrollbar>
              <el-collapse v-model="dataValueCollapse" @change="handleValueChange">
                <el-collapse-item name="Home">
                  <template #title>
                    <el-tag>{{ $t('menus.首页') }}</el-tag>
                  </template>
                  <el-form label-width="auto" label-position="right">
                    <el-form-item>
                      <el-checkbox-group v-model="formData.value.home.module">
                        <el-checkbox v-for="(item, index) in homeModuleTypeList" :key="index" :label="item.value" border>{{ $t('page.' + item.label ) }}</el-checkbox>
                      </el-checkbox-group>
                    </el-form-item>
                  </el-form>
                </el-collapse-item>
              </el-collapse>
            </el-scrollbar>
          </el-tab-pane>
        </el-tabs>
      </div>
    </template>
    <template #footer>
      <div class="flex justify-end">
        <el-button @click="cancelClick">{{ $t('buttons.buttonCancel') }}</el-button>
        <el-button type="primary" @click="confirmClick">{{ $t('buttons.buttonConfirm') }}</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<style lang="scss">
.role-drawer {

  .el-drawer__header {
    margin: 0;
    padding: 15px var(--el-space);
    border-bottom: 1px solid var(--el-border-color-extra-light);
  }

  .el-drawer__footer {
    margin: 0;
    padding: 15px var(--el-space);
    border-top: 1px solid var(--el-border-color-extra-light);
  }

  .el-drawer__body {
    position: relative;
    display: flex;
    flex-direction: column;
    padding: 0;

    .tab-wrap {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      overflow: hidden;

      .el-tabs {
        height: 100%;

        .el-tabs__nav-wrap::after {
          background-color: var(--el-border-color-lighter);
        }

        &.el-tabs--left .el-tabs__header.is-left {
          margin-right: 0;
        }

        &.el-tabs--left .el-tabs__nav-wrap.is-left::after,
        &.el-tabs--left .el-tabs__active-bar.is-left {
          width: 1px;
        }

        .el-tabs__content {
          height: 100%;

          .el-tab-pane {
            display: flex;
            width: 100%;
            height: 100%;
            overflow: hidden;

            .el-form {
              margin: 0 -6px;
            }

            .table-content {
              position: relative;
              flex: 1;
              padding: 0 6px;
            }

            >.el-scrollbar {
              flex: 1;

              >.el-scrollbar__wrap {
                padding: var(--el-space);
              }

              .el-collapse {
                margin-top: -12px;
                border-top: none;
                border-bottom: none;

                .el-collapse-item {
                  &:last-child {
                    .el-collapse-item__header {
                      border-bottom: none !important;
                    }

                    .el-collapse-item__wrap {
                      border-bottom: none !important;
                    }

                    &.is-active {
                      .el-collapse-item__header {
                        border-bottom: none !important;
                      }

                      .el-collapse-item__wrap {
                        border-bottom: none !important;
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }

      .el-collapse-item__content {
        padding-bottom: 14px;
      }
    }
  }
}

.table-layout {
  position: relative;
  display: flex;
  flex: 1;
  padding: var(--el-space);

  .table-wrapper {
    position: relative;
    flex: 1;
  }

  .table-wrap {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;

    .el-table {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
